<?php

namespace App\Listeners;

use App\Events\ConfirmReceiptEvent;
use App\Forms\ConfigForms;
use App\Forms\OrderForms;
use App\Forms\UserForms;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class UserLevelListeners
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ConfirmReceiptEvent  $event
     * @return void
     */
    public function handle(ConfirmReceiptEvent $event)
    {
        //累增用户订单数量 总金额  总分销金额
        $order = $event->order;

        $confirmForms = new ConfigForms();

        $levelAmount = $confirmForms->getDetail('distributor_amount')->value;

        $levelChildrenCount = $confirmForms->getDetail('distributor_children')->value;

        $userForms = new UserForms();

        $user = $userForms->getUserDetail($order->uid);


        if((bcadd($user->order_amount, $order->pay_amount) >= $levelAmount)
            && ($userForms->getChildrenCount($order->uid) >= $levelChildrenCount)
            && $user->level == User::L_DEFAULT ){
            $update['level'] = User::L_DISTRIBUTOR;
        }

        $update['order_amount'] = bcadd($user->order_amount, $order->pay_amount,2);
        $update['commission_amount'] = bcadd($user->commission_amount, $order->commission_amount,2);
        $update['order_count'] = $user->order_count + 1;

        $user->update($update);
    }
}
